package com.frxuexi.sign

import android.os.Bundle
import android.util.Log
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material3.Button
import androidx.compose.material3.Icon
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp
import androidx.compose.ui.viewinterop.AndroidView
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavController
import androidx.navigation.NavDestination
import androidx.navigation.NavHostController
import com.baidu.location.BDAbstractLocationListener
import com.baidu.location.BDLocation
import com.baidu.location.LocationClient
import com.baidu.location.LocationClientOption
import com.baidu.mapapi.CoordType
import com.baidu.mapapi.SDKInitializer
import com.baidu.mapapi.common.BaiduMapSDKException
import com.baidu.mapapi.map.BaiduMap
import com.baidu.mapapi.map.MapStatusUpdateFactory
import com.baidu.mapapi.map.MapView
import com.baidu.mapapi.map.MyLocationData
import com.baidu.mapapi.model.LatLng
import com.blankj.utilcode.util.ToastUtils
import com.frxuexi.lib_base.BaseApp
import com.frxuexi.lib_base.MyNavTo
import com.frxuexi.lib_base.NavPath
import com.frxuexi.lib_base.UiState
import com.frxuexi.sign.intent.SignIntent
import com.frxuexi.sign.viewmodel.SignViewModel
import com.tencent.mmkv.MMKV
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch


var mapView:MapView?=null
lateinit var mBaiduMap: BaiduMap
lateinit var mLocationClient:LocationClient
var myLocationListener:MyLocationListener?=null
@Composable
fun SignCommitPage(navHostController: NavHostController,
                   vm:SignViewModel= hiltViewModel(),
                   scope: CoroutineScope = rememberCoroutineScope()) {
    initMap()
    Column {
        Row(
            horizontalArrangement = Arrangement.SpaceBetween,
            verticalAlignment = Alignment.CenterVertically,
            modifier = Modifier
                .fillMaxWidth()
                .height(50.dp)
                .padding(10.dp)
        ) {
            Icon(imageVector = Icons.Default.ArrowBack,
                contentDescription = "",
                modifier = Modifier.clickable {
                    navHostController.popBackStack()
                })
            Text(text = "签到")
            Text(text = "确定", color = Color.White, modifier = Modifier
                .background(Color.Blue, RoundedCornerShape(10.dp))
                .padding(horizontal = 10.dp, vertical = 3.dp)
                .clickable {
                    val loc = MMKV
                        .defaultMMKV()
                        .decodeString("location", "")
                    if (loc.isNullOrEmpty()) {
                        return@clickable
                    }
                    val split = loc.split(",")
                    val map = mapOf<String, Any>(
                        Pair("userId", 1),
                        Pair("SignLat", split[0]),
                        Pair("SignLong", split[1])
                    )
                    vm.sendIntent(SignIntent.sign(map))
                    navHostController.popBackStack()
                })

        }
        AndroidView( modifier = Modifier.fillMaxSize(),factory = {
            mapView = MapView(it)
            mBaiduMap= mapView!!.map
            //开启地图的定位图层
            mBaiduMap.isMyLocationEnabled=true
            mapView!!
        })


    }

    LaunchedEffect(key1 = "", block = {

        scope.launch {
            vm.uiState.collect{
                when(it){
                    is UiState.onSuccess->{
                        ToastUtils.showLong("打卡成功")

                    }
                    is UiState.onError->{
                        Log.i("===",it.msg)
                    }
                    else->{}
                }
            }
        }

        navHostController.addOnDestinationChangedListener(object :NavController.OnDestinationChangedListener{
            override fun onDestinationChanged(
                controller: NavController,
                destination: NavDestination,
                arguments: Bundle?
            ) {

                //把回退的router也加入集合
                MyNavTo.list.add(destination.route.toString())

                val index = MyNavTo.list.lastIndexOf(NavPath.SIGN)
                //判断是否是从签到页面到签到列表页面
                if(destination.route.toString()==NavPath.SIGN && MyNavTo.list.get(index-1)==NavPath.SIGN_COMMIT){
                    Log.i("===","从："+destination.route.toString()+"，到"+MyNavTo.list.get(index-1))
                    mLocationClient.unRegisterLocationListener(myLocationListener)
                    myLocationListener=null
                    mLocationClient.stop();
                    mBaiduMap.setMyLocationEnabled(false);
                    mapView?.onDestroy();
                    mapView = null;
                }
            }

        })
    })
}

fun initMap(){
    LocationClient.setAgreePrivacy(true);
// 是否同意隐私政策，默认为false
    // 是否同意隐私政策，默认为false
    SDKInitializer.setAgreePrivacy(BaseApp.context, true)

    try {
        // 在使用 SDK 各组间之前初始化 context 信息，传入 ApplicationContext
        SDKInitializer.initialize(BaseApp.context)
    } catch (e: BaiduMapSDKException) {
    }

    //定位初始化
    //定位初始化
    mLocationClient = LocationClient(BaseApp.context)

//通过LocationClientOption设置LocationClient相关参数

//通过LocationClientOption设置LocationClient相关参数
    val option = LocationClientOption()
    option.isOpenGps = true // 打开gps

    option.setCoorType("bd09ll") // 设置坐标类型

    option.setScanSpan(1000)
//设置locationClientOption

//设置locationClientOption
    mLocationClient.setLocOption(option)

//注册LocationListener监听器

//注册LocationListener监听器
    myLocationListener = MyLocationListener()
    mLocationClient.registerLocationListener(myLocationListener)
//开启地图定位图层
//开启地图定位图层
    mLocationClient.start()
}


class MyLocationListener : BDAbstractLocationListener() {
    override fun onReceiveLocation(location: BDLocation) {
        //mapView 销毁后不在处理新接收的位置
        if (location == null || mapView == null) {
            return
        }
        val latitude = location.latitude
        val longitude = location.longitude
        Log.i("===","$latitude,$longitude")
        MMKV.defaultMMKV().encode("location","$latitude,$longitude")
        //定位蓝点额外加的
        var ll = LatLng(latitude, longitude);
        val update = MapStatusUpdateFactory.newLatLngZoom(ll, 18f);
        mBaiduMap.animateMapStatus(update);

        val locData = MyLocationData.Builder()
            .accuracy(location.radius) // 此处设置开发者获取到的方向信息，顺时针0-360
            .direction(location.direction).latitude(latitude)
            .longitude(longitude).build()
        mBaiduMap.setMyLocationData(locData)
    }
}